package com.guoranhao.tool.utils;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Description: Jackson Util
 * All Rights Reserved.
 * @version 1.0  2016年8月15日 下午2:50:15  by 代鹏（daipeng.456@gmail.com）创建
 */
public class JsonUtil {
	
	private static ObjectMapper mapper = new ObjectMapper();
	private final static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
	
	static 
	{	
		mapper.setSerializationInclusion(Inclusion.NON_NULL);
		mapper.disable(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
	}

	public static String Object2Json(Object o) {
		String s = null;
		try {
			if (o != null) {
				s = mapper.writeValueAsString(o);
			}
		} catch (JsonGenerationException e) {
			logger.error("Object2Json json generation error",e);
		} catch (JsonMappingException e) {
			logger.error("Object2Json json mapping error",e);
		} catch (IOException e) {
			logger.error("Object2Json io error",e);
		}
		return s;
	}

	public static <T> T Json2Object(String json, Class<T> c) {
		T t = null;
		try {
			if (StringUtils.isNotBlank(json)) {
				t = mapper.readValue(json, c);
			}
		} catch (JsonParseException e) {
			logger.error("Json2Object json generation error",e);
		} catch (JsonMappingException e) {
			logger.error("Json2Object json mapping error",e);
		} catch (IOException e) {
			logger.error("Json2Object io error",e);
		}
		return t;
	}
	
}
